package net.zjitc.controller;

import net.zjitc.common.Msg;
import net.zjitc.common.ServiceResponse;
import net.zjitc.pojo.User;
import net.zjitc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.crypto.Data;
import java.util.Date;
import java.util.List;

/**
 * @Author admin
 * @Date 2019/4/24 14:30
 */
@Controller

public class Usercontroller {
    @Autowired
    UserService userService;

    @RequestMapping(value = "/register")
    public String register(Model model, User user){
        String password = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(password);
        user.setRole("普通用户");
        Date date = new Date();
        userService.register(user);
        return "/suyaoyajiu/tishi1.jsp";
    }
    @RequestMapping(value = "/checkEmail")
    @ResponseBody
    public Msg checkEmail(@RequestBody User user){
        return userService.checkEmail(user);
    }
    @RequestMapping(value = "/checkUsername")
    @ResponseBody
    public Msg checkUsername(@RequestBody User user){
        return userService.checkUsername(user);
    }
    @RequestMapping(value = "/login")
    public String login(Model model, User user,HttpServletRequest request){
        String password = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());

        User fpassword = userService.findByName(user.getUsername());
        System.out.println(fpassword);
        if (fpassword==null){
            model.addAttribute("msg","用户名或密码错误");
            return "suyaoyajiu/login.jsp";
        }

        if (password.equals(fpassword.getPassword())){
            model.addAttribute("suss","登录成功");
            HttpSession session = request.getSession();
            session.setAttribute("user",user);

            return "suyaoyajiu/index.jsp";
        }
        model.addAttribute("msg","用户名或密码错误（密码）");
        return "suyaoyajiu/login.jsp";
    }
    @RequestMapping("/logout")
    public String logout(HttpServletRequest request){
        HttpSession session = request.getSession();
        session.removeAttribute("user");
        return "/index.jsp";
    }
}
